package data

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

type user struct {
	username string
	password string
}

var db *sql.DB //连接池对象
func Connect() (err error) {
	fmt.Println("开始连接数据库~")
	//数据库
	//用户名:密码@tcp(ip:端口)/数据库的名字
	dsn := "root:3363@tcp(116.198.241.238:3306)/userchat"
	//连接数据集
	db, err = sql.Open("mysql", dsn) //open不会检验用户名和密码
	if err != nil {
		fmt.Printf("dsn:%s invalid,err:%v\n", dsn, err)
		return
	}
	err = db.Ping() //尝试连接数据库
	if err != nil {
		fmt.Printf("open %s faild,err:%v\n", dsn, err)
		return
	}
	fmt.Println("连接数据库成功~")
	return
}

func Query(username string) (password string) {
	//1.查询单挑记录的sql语句  ?是参数
	sqlStr := "select username,password from user where username=?;"
	//2.执行
	rowObj := db.QueryRow(sqlStr, username) //返回一条记录
	//如果没有找到数据则 所有值都为0
	//3.拿到结果
	var u1 user
	rowObj.Scan(&u1.username, &u1.password)
	return u1.password
}

func Insert(username string, password string, ip string) int {
	if Query(username) != "" {
		return 1
	}
	sqlStr := `insert into user(username,password, ip) values(?,?,?)` //sql语句
	_, err := db.Exec(sqlStr, username, password, ip)                 //执行sql语句 不返回数据集
	if err != nil {
		fmt.Printf("insert failed,err:%v\n", err)
		return 0
	}
	return 2
}

func AmendIP(username string, ip string) {
	sqlStr := `update user set ip=? where username=?`
	_, err := db.Exec(sqlStr, ip, username)
	if err != nil {
		fmt.Printf("update failed ,err:%v\n", err)
		return
	}
}

func Verification(username string, password string) int {
	myPassword := Query(username)
	if myPassword == "" {
		return 1
	}
	if password != myPassword {
		return 2
	}
	return 0
}
